package org.dromara.web.controller;


import cn.dev33.satoken.annotation.SaCheckDisable;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.dromara.common.core.domain.R;
import org.dromara.web.domain.User;
import org.dromara.web.domain.WechatConfig;
import org.dromara.web.domain.vo.UserLoginVo;
import org.dromara.web.domain.bo.UserLoginBo;
import org.dromara.web.mapper.UserMapper;
import org.dromara.web.mapper.WechatConfigMapper;
import org.dromara.web.utils.RSAUtils;
import org.redisson.api.RSemaphore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@SaIgnore
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
public class UserController {


    @Autowired
    private WechatConfigMapper wechatConfigMapper;

    @Autowired
    private UserMapper userMapper;

    @Value("${ruoyi.publicKey}")
    private String publicKey;

    @Value("${ruoyi.privateKey}")
    private String privateKey;

    @GetMapping("/userInfo")
    public R<User> userInfo() {
        String uid = StpUtil.getLoginIdAsString();
        String tenantId = StpUtil.getLoginDevice();
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("uid", uid).eq("tenant_id", tenantId));
        return R.ok(user);
    }


    /**
     * 账号密码登录 暂时不需要openId
     * @param loginUser
     * @return
     * @throws Exception
     */
    @PostMapping("/login")
    @SaIgnore
    public R<Map<Object, Object>> login(@RequestBody @Validated UserLoginBo loginUser) throws Exception {
        return handleNewUser(loginUser);
    }


    private R<Map<Object, Object>> handleNewUser(UserLoginBo loginUser) throws Exception {
        String password = RSAUtils.decrypt(loginUser.getPassword(), RSAUtils.getPrivateKeyFromString(privateKey));
        log.info("解密后的密码: {}", password);
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("uid", loginUser.getUid())
            .eq("tenant_id", loginUser.getTenantId())
        );
        if (user != null) {
            String dbPassword = RSAUtils.decrypt(user.getPassword(), RSAUtils.getPrivateKeyFromString(privateKey));
            if (password.equals(dbPassword)) {
                return R.ok(userLogin(user));
            }else {
                return R.fail("密码错误");
            }
        }else {
            return R.fail("用户不存在");
        }
    }






    private Map<Object, Object> userLogin(User user) {
        SaLoginModel loginModel = new SaLoginModel();
        loginModel.setDevice(user.getTenantId());
        StpUtil.checkDisable(user.getUid());
        if (user.getStatus() == -1) {
            throw new RuntimeException("账号已封禁");
        }
        StpUtil.login(user.getUid(), loginModel);
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        Map<Object, Object> userInfo = new HashMap<>();

        userInfo.put("user", user);
        userInfo.put("token", tokenInfo);

        return userInfo;
    }

}
